<template>
  <div>
    <!--    查询功能-->
    <div style="margin-bottom: 5px">
        <!-- 下拉框部门查询 -->
      <el-select v-model="deptId" placeholder="请选择部门" readonly>
        <el-option
          v-for="item in deptAll"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        ></el-option>
      </el-select>
      <!-- 下拉框部门角色查询 -->
      <el-select v-model="roleId" placeholder="请选择部门角色" readonly>
        <el-option
          v-for="item in roleAll"
          :key="item.id"
          :label="item.role"
          :value="item.id"
        ></el-option>
      </el-select>
      <!-- 用户名称查询 -->
       <el-input
        v-model="userName"
        @keyup.enter.native="queryAll"
        placeholder="请输入用户名称"
        suffix-icon="el-icon-search"
        style="width: 190px; margin-left: 5px"
      ></el-input>
      <el-button type="primary" style="margin-left: 5px" @click="queryAll"
        >查询</el-button>
        <!-- 下拉框部门 -->
      <el-select v-model="deptIds" placeholder="请选择部门" readonly>
        <el-option
          v-for="item in deptName"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        ></el-option>
      </el-select>
      <!-- 用户名称查询 -->
      <el-input
        v-model="userId"
        @keyup.enter.native="unbinID"
        placeholder="请输入用户id"
        suffix-icon="el-icon-search"
        style="width: 190px; margin-left: 5px"
      ></el-input>
       <!--      解绑按钮-->
       <el-button type="primary" style="margin-left: 5px" @click="unbinID"
        >解绑</el-button>
      <!--      绑定或更新按钮-->
      <el-button type="primary" style="margin-left: 5px" @click="add"
        >绑定或更新</el-button>
      <!--      重置按钮-->
      <el-button type="success" @click="resetParam">重置</el-button>
    </div>

    <!--    列表展示-->
    <el-table
      :data="departmentData"
      :header-cell-style="{ background: '#D3D3D3FF', color: '#555555' }"
    >
    <el-table-column prop="id" label="id" width="160"> </el-table-column>
    <el-table-column label="部门名称" width="100">
        <template slot-scope="scope">
          {{ getDeptName(scope.row.deptId) }}
        </template>
      </el-table-column>
      <el-table-column label="职位" width="100">
        <template slot-scope="scope">
          {{ getRoleName(scope.row.roleId) }}
        </template>
      </el-table-column>
      <el-table-column prop="userId" label="用户id" width="160"> </el-table-column>
      <el-table-column prop="userName" label="用户名称" width="100"> </el-table-column>
      <el-table-column prop="gmtCreate" label="创建时间" width="180">
      </el-table-column>
      <el-table-column prop="operate" label="操作">
        <template slot-scope="scope">
          <el-button size="small" type="success" @click="mod(scope.row)"
            >编辑</el-button
          >
          <el-popconfirm
            confirm-button-text="确定"
            cancel-button-text="取消"
            icon="el-icon-info"
            icon-color="red"
            title="这是一段内容确定删除吗？"
            @confirm="del(scope.row.id)"
            style="margin-left: 5px"
          >
            <el-button slot="reference" size="small" type="danger"
              >删除</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      title="绑定或更新用户与部门信息"
      :visible.sync="centerDialogVisible"
      width="30%"
      center
      :before-close="handleClose">
      <el-dialog
            width="50%"
            title="成员选择"
            :visible.sync="innerVisible"
            append-to-body>

          <SelectUser @doSelectUser="doSelectUser"></SelectUser>
          <span slot="footer" class="dialog-footer">
            <el-button @click="innerVisible = false">取 消</el-button>
            <el-button type="primary" @click="confirmUser">确 定</el-button>
          </span>
        </el-dialog>
      <!--      绑定成员信息表单-->
      <el-form ref="form" :rules="rules" :model="form" label-width="80px">
        <el-form-item label="部门">
          <el-select v-model="form.deptId" placeholder="请选择部门" >
            <el-option
              v-for="item in deptAll"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门角色">
          <el-select v-model="form.roleId" placeholder="请选择部门" >
            <el-option
              v-for="item in roleAll"
              :key="item.id"
              :label="item.role"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户名称" prop="userName">
          <el-col :span="15">
            <el-input v-model="form.userName" readonly @click.native="selectUser"></el-input>
          </el-col>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </span>
    </el-dialog>
    <div style="margin-top: 10px; text-align: center">
      <div class="pagination-container">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[5, 10, 20, 30]"
          :page-size="limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      ></el-pagination>
     </div>

    </div>
  </div>
</template>

<script>
import SelectUser from "@/page/registrationService/SelectUser";
import { queryAll,deptQueryAll,roleQueryAll,del,add,unbindUserDept } from "@/api/departmentalServices/departmentUserRelationship";
export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: "departmentUserRelationship",
  components: {SelectUser},
  data() {
    return {
      currentRow: {},
      tempUser: {},
      departmentData: [],
      deptName:[],
      deptAll: [],
      roleAll: [],
      centerDialogVisible: false,
      page: 1,
      limit: 5,
      num: 1,
      total: 0,
      innerVisible: false,
      deptId:"",
      deptIds:"",
      roleId: "",
      userId:"",
      userName:"",
      form: {
        id:"",
        deptId:"",
        roleId: "",
        userId:"",
        userName:""
      },
      rules: {
          role: [{ required: true, message: "请输入姓名", trigger: "blur" }],
      },
    };
  },
  methods: {
    handleSizeChange(newSize) {
      this.limit = newSize;
      this.page = 1;  // Reset to first page with new page size
      this.queryAll();
    },
    handleCurrentChange(newPage) {
      this.page = newPage;
      this.queryAll();
    },
    selectCurrentChange(val) {
      this.currentRow = val;
    },
    //重置表单
    resetForm() {
      this.$refs.form.resetFields();
      //将计数器的数字重置为1
      this.num = 1;
    },
//将展示列表的部门id换成部门名称
getDeptName(deptId) {
      const dept = this.deptAll.find((c) => c.id === deptId);
      return dept ? dept.name : "未选择部门";
    },
    getDeptNames(deptIds) {
      const dept = this.deptName.find((c) => c.id === deptIds);
      return dept ? dept.name : "未选择部门";
    },
    //将展示列表的部门角色id换成部门名称
getRoleName(roleId) {
      const roles = this.roleAll.find((a) => a.id === roleId);
      return roles ? roles.role : "未选择部门角色";
    },
    //新增按钮
    add() {
      this.centerDialogVisible = true;
      this.$nextTick(() => {
        this.resetForm();
      });
    },
    //删除
    del(id) {
      del(id).then((res) => {
        if (res.code === 20000) {
          this.$message({
            message: "删除成功",
            type: "success",
          });
          this.centerDialogVisible = false;
          this.queryAll();
        } else {
          this.$message({
            message: "删除失败",
            type: "error",
          });
        }
      });
    },
    doSave() {
      add(this.form).then((res) => {
        if (res.code === 20000) {
          this.$message({
            message: "增加成功",
            type: "success",
          });
          this.centerDialogVisible = false;
          this.queryAll();
          this.resetForm();
        } else {
          this.$message({
            message: "增加失败",
            type: "error",
          });
        }
      });
    },
    selectUser() {
      this.innerVisible = true
    },
    confirmUser() {
      this.form.userName = this.tempUser.name
      this.form.userId = this.tempUser.userId
      this.innerVisible = false
    },
    doSelectUser(val) {
      console.log(val)
      this.tempUser = val

    },
    //修改
    mod(row) {
      this.centerDialogVisible = true;
      this.$nextTick(() => {
        //赋值到表单
        this.id = row.id;
        this.form.deptId = row.deptId;
        this.form.roleId = row.roleId
        this.form.userName = row.userName;
      });
    },
    doMod( ) {
      add(this.form).then((res) => {
        if (res.code === 20000) {
          this.rec
          this.$message({
            message: "修改成功",
            type: "success",
          });
          this.centerDialogVisible = false;
          this.queryAll();
          this.resetForm();
        } else {
          this.$message({
            message: "修改失败",
            type: "error",
          });
          
        }
      });
    },
    save() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.id) {
            //如果有id则修改
            this.doMod();
          } else {
            //否则增加
            this.doSave();
          }
        } else {
          this.$message({
            message: "操作失败",
            type: "error",
          });
          return false;
        }
      });
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(() => {
          done();
        })
        .catch(() => {});
    },
    resetParam() {
      this.deptId = "";
      this.roleId = "";
      this.userName = "";
      this.userId = "";
      this.deptName[0] = "";
      this.queryAll();
    },
    unbinID() { 
      if(!this.userId && !this.deptIds){
        this.$message({
            message: "请选择解绑数据",
            type: "error",
          });
        return
      }
      unbindUserDept(this.userId,this.deptIds).then((res) => {
        if (res.code === 20000) {
                this.queryAll();
          this.$message({
            message: "解绑成功",
            type: "success",
          });
          this.centerDialogVisible = false;
          this.userId = "";
          this.deptIds = "";
        } else {
          this.$message({
            message: "解绑失败",
            type: "error",
          });
        }
      });
    },
    queryAll() {
      const params = {
        deptId: this.deptId,
        roleId: this.roleId,
        userName: this.userName
      };
      queryAll(this.page, this.limit, params).then((res) => {
        if (res.code === 20000) {
          this.departmentData = res.data.list.records;
          this.total = res.data.list.total;
        } 
      });
    },
    deptData() {
      deptQueryAll()
        .then((res) => {
          this.deptAll = res.data.depts.map((item) => ({
            id: item.id,
            name: item.name,
          }));
            this.deptName = res.data.depts.map((item) => ({
            id: item.id,
            name: item.name
        }));
      })
        .catch((error) => {
          console.error("Error fetching region data:", error);
        });
    },
    roleData() {
      roleQueryAll()
        .then((res) => {
          this.roleAll = res.data.roles.map((item) => ({
            id: item.id,
            role: item.role,
          }));
        })
        .catch((error) => {
          console.error("Error fetching region data:", error);
        });
    },
  },
  beforeMount() { 
    this.queryAll();
    this.deptData();
    this.roleData();
  },
};
</script>

<style scoped>
.pagination-wrapper {
  position: fixed;
  bottom: 0;
  width: 100%;
  /*background-color: #f5f5f5;*/
  padding: 10px 20px;
  /*box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);*/
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  max-width: 800px; /* 设置最大宽度以避免在大屏幕上过分拉伸 */
  margin: 0 30%; /* 居中显示分页组件 */
}
</style>
